import React, { useEffect, useState } from 'react'
import { Card, Form, Button, Input, Select, Table, Row, Col, Tooltip, message } from 'antd'
import { SearchOutlined } from "@ant-design/icons"
import { useNavigate } from 'react-router-dom'

import {
  getHospitalListRequest,
  getProvinceInHosList,
  getCityOrBlockReruest,
  hosListCheckedStatusRequest,
} from "@api/hospital/hospitalList"

import type {
  getHosListReqParamstpe,
  getHosListReqContentType,
  hospitalListItemsType,
  getProvinceReqReturn
} from "@api/hospital/model/hospitalListType"


export default function HospitalList() {

  //拿到表单实例
  const [from] = Form.useForm()

  //编程式路由导航跳转到医院详情页面
  const navigate = useNavigate()

  //保存状态 控制表格加载等待动画
  const [islogin, setIslogin] = useState(false)
  //保存状态 控制当前页码的改变 
  const [page, setPage] = useState(1)
  //保存状态 控制每页数据条数的改变 
  const [limit, setLimit] = useState(10)
  //保存状态 初始化总数据条数 请求完成后改变总数据条数
  const [total, setTotal] = useState(0)

  //初始化数组 
  const [hospitalList, setHospital] = useState<getHosListReqContentType>([])
  //收集表单数据
  const [searchParams, setSearchParams] = useState<getHosListReqParamstpe>({})
  //保存省数据
  const [province, setProvince] = useState<getProvinceReqReturn>([])
  //保存类型数据
  const [type, setType] = useState<getProvinceReqReturn>([])
  //保存市数据
  const [city, setCity] = useState<getProvinceReqReturn>([])
  //保存区数据
  const [block, setBlock] = useState<getProvinceReqReturn>([])
  //保存状态切换之后查询渲染
  const [resetRender , setRestRender] = useState(true)




  //1.刚进页面发送请求渲染页面
  useEffect(() => {
    (async () => {
      //发送请求等待转圈圈
      setIslogin(true)

      //请求分页列表
      const result = await getHospitalListRequest(page, limit, searchParams)

      //请求成功修改总数据条数
      setTotal(result.totalElements)

      //请求成功修改数组渲染页面
      setHospital(result.content)


      //请求结束停止转圈圈
      setIslogin(false)
    })()
  }, [page, limit, searchParams , resetRender])


  //2.初始化请求省数据渲染到下拉框中
  useEffect(() => {
    (async () => {
      //请求省数据
      const result = await getProvinceInHosList()

      //保存在状态中
      setProvince(result)

    })()
  }, [])


  //3.初始化请求类型渲染到下拉框中
  useEffect(() => {
    (async () => {
      //请求类型数据
      const result = await getCityOrBlockReruest("10000")

      //保存在状态中
      setType(result)

    })()
  }, [])



  //表格列的配置描述
  const columns = [
    {
      title: '序号',
      width: 60,
      aligin: "center" as "center", //居中
      dataIndex: 'index',
      render(_: any, __: any, index: number) {
        return index + 1
      }
    },

    {
      title: '医院logo',
      dataIndex: "hosname",
      aligin: "center" as "center", //居中
      render(_: any, data: hospitalListItemsType) {
        return <img width={100} src={`data:image/jpeg;base64,${data.logoData}`} alt="" />
      }
    },

    {
      title: '医院名称',
      dataIndex: "hosname",
      aligin: "center" as "center", //居中
    },

    {
      title: '等级',
      aligin: "center" as "center", //居中
      render(_: any, data: hospitalListItemsType) {
        return data.param.fullAddress
      }
    },

    {
      title: '详细地址',
      aligin: "center" as "center", //居中
      render(_: any, data: hospitalListItemsType) {
        return data.param.hostypeString
      }
    },

    {
      title: '状态',
      aligin: "center" as "center", //居中
      render(_: any, data: hospitalListItemsType) {
        return data.status === 0 ? "下线" : "上线"
      }
    },

    {
      title: '创建时间',
      dataIndex: "createTime"

    },

    {
      title: '操作',
      width: 240,
      fixed: "right" as "right",
      dataIndex: "do",
      render(_: any, data: hospitalListItemsType) {
        //拿到当前这条数据对应的id
        const { id } = data;
        //拿到当前这条数据对应的status
        const { status } = data;

        return (
          <div>
            <Tooltip title={"查看"}>
              <Button type='primary' onClick={goHospitalListHandle(id)}>查看</Button>
            </Tooltip>

            <Tooltip title={"排班"}>
              <Button type='primary'>排班</Button>
            </Tooltip>

            <Tooltip title={status === 0 ? "上线" : "下线"}>
              <Button type='primary' onClick={checkedStatus(id, status === 0 ? 1 : 0)}>
                {status === 0 ? "上线" : "下线"}
              </Button>
            </Tooltip>
          </div >
        )
      }
    }
  ];


  //1.点击页码的回调函数
  const changePageHandle = (page: number, limit: number) => {
    //改变状态查询渲染
    setPage(page)
    setLimit(limit)
  }

  //2.点击查询的回调函数
  const searchHosListHandle = (finishValue: getHosListReqParamstpe) => {
    setSearchParams(finishValue)
  }

  //3.点击省获取市的回调函数
  const getCityHandle = async (id: string) => {
    //发送获取市的请求
    const result = await getCityOrBlockReruest(id)

    //拿到的市的数据保存在状态
    setCity(result)

    //再次点击省清空市和区的输入框
    from.setFieldsValue({ cityCode: "", districtCode: "" })

    //再次点击也要把区的数据清除 市不用清除
    setBlock([])

  }

  //4.点击省市获取区的回调函数
  const getBlockHandle = async (id: string) => {
    //发送获取市的请求
    const result = await getCityOrBlockReruest(id)

    //拿到的市的数据保存在状态
    setBlock(result)

    //再次点击市把区的输入框内容清空
    from.setFieldsValue({ districtCode: "" })

  }

  //5.点击清除的回调函数
  const clearHabdle = () => {
    //把保存表单数据的状态清空就会查询渲染
    setSearchParams({})
  }


  //6.点击查看的回调函数
  const goHospitalListHandle = (id: string) => {
    return () => {
      navigate(`/syt/hospital/hospitalshow/${id}`)
    }
  }

  //7.点击上/下线的回调函数
  const checkedStatus = (id: string, status: 0 | 1) => {
    return async () => {
      //发送切换状态请求
      await hosListCheckedStatusRequest(id, status)

      if (status === 0) {
        message.success("下线成功!")
      } else {
        message.success("上线成功!")
      }

      //查询渲染
      setRestRender(!resetRender)

    }
  }

  //8.点击排班的回调函数
  





  return (
    <div>
      <Card>

        <Form
          name="basic"
          //表单提交事件
          onFinish={searchHosListHandle}
          //绑定表单实例
          form={from}
        >
          <Row gutter={10}>
            <Col span={4}>
              <Form.Item
                name="provinceCode"
              >
                <Select
                  placeholder="请输入省份"
                  allowClear
                  //点击省的回调 第一个参数是当前value
                  onChange={getCityHandle}
                >
                  {
                    province.map((item) => {
                      return <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item
                name="cityCode"
              >
                <Select
                  placeholder="请输入市"
                  allowClear
                  //点击市的回调 第一个参数是当前value
                  onChange={getBlockHandle}
                >
                  {
                    city.map((item) => {
                      return <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item
                name="districtCode"
              >
                <Select
                  placeholder="请输入县/区"
                  allowClear
                >
                  {
                    block.map((item) => {
                      return <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item
                name="hosname"
              >
                <Input placeholder="医院名称" />
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item
                name="hoscode"
              >
                <Input placeholder='医院编号' />
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item
                name="hostype"
              >
                <Select
                  placeholder="医院类型"
                  allowClear
                >
                  {
                    type.map((item) => {
                      return <Select.Option value={item.value} key={item.id}>{item.name}</Select.Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={10}>
            <Col span={4}>
              <Form.Item
                name="status"
              >
                <Select
                  placeholder="医院状态"
                  allowClear
                >
                  <Select.Option value={1}>上线</Select.Option>
                  <Select.Option value={0}>下线</Select.Option>
                </Select>
              </Form.Item>
            </Col>

            <Col span={2}>
              <Form.Item >
                <Button type="primary" htmlType="submit" icon={<SearchOutlined />} >
                  查询
                </Button>
              </Form.Item>
            </Col>

            <Col span={2}>
              <Form.Item >
                <Button type="default" htmlType="reset" onClick={clearHabdle}>
                  清空
                </Button>
              </Form.Item>
            </Col>

          </Row>

        </Form>

        <Table
          style={{ marginTop: "30px" }}
          columns={columns}
          dataSource={hospitalList}
          scroll={{ x: 1100 }}
          bordered
          //在table中 要求dataSource中有key属性,但是如果真的没有key 则可以使用rowKey属性指定dataSource中的一个属性作为Key
          rowKey="id"

          //表格加载等待动画
          loading={islogin}

          //分页器
          pagination={{
            //页码的配置：当前页码
            current: page,
            //每页条数
            pageSize: limit,
            // 总数据的数量
            total: total,
            //展示更改每页条数的选项(默认total大于50条的时候开启)
            pageSizeOptions: [1, 2, 3, 4, 5, 6, 7, 8, 9],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,

            //展示总数据
            showTotal(total) {
              return `数据有${total}条`
            },

            //页码改变的函数
            onChange: changePageHandle

          }}
        />

      </Card>
    </div>
  )
}
